package com.it.data_linkedList.single;

import com.it.data_tree.util.ColorPrintln;

import java.util.Iterator;

/**
 * @Author: Coke
 * @DateTime: 2023/05/14/11:32
 * @注释: 单项链表
 **/
public class SingleLinkedList implements Iterable<Integer> {
    // 头指针
    SingleNode head = null;
    // 尾指针
    SingleNode last = new SingleNode(- 1, null);
    
    /**
     * @param value:
     * @return SingleNode
     * @作者: Coke
     * @注释: 头插法
     * @DateTime: 2023/5/14 11:49
     */
    public SingleNode add (int value) {
        // 1. 链表为空
//        head = new SingleNode(value, null);
        // 2. 链表不为空
        head = new SingleNode(value, head);
        return head;
    }
    
    /**
     * @param value:
     * @return SingleNode
     * @作者: Coke
     * @注释: 尾插法
     * @DateTime: 2023/5/14 18:31
     */
    public SingleNode addLast (int value) {
        SingleNode newNode = new SingleNode(value, null);
        // 1. 链表为空
        if (head == null) {
            head = newNode;
            newNode.next = last;
            last.next = newNode;
            // 2. 链表不为空
        } else {
            last.next.next = newNode;
            newNode.next = last;
            last.next = newNode;
        }
        return head;
    }
    
    
    /**
     * @return void
     * @作者: Coke
     * @注释: 遍历链表
     * @DateTime: 2023/5/14 15:06
     */
    public void print () {
        SingleNode node = head;
        StringBuilder str = new StringBuilder();
        while (node != null && node != last) {
            if ("".contentEquals(str)) {
                str.append(node.value);
            } else {
                str.append(", ").append(node.value);
            }
            node = node.next;
        }
        ColorPrintln.greenPrintln(str);
    }
    
    /**
     * @return Iterator<Integer>
     * @作者: Coke
     * @注释: 增强for遍历
     * @DateTime: 2023/5/14 15:20
     */
    @Override
    public Iterator<Integer> iterator () {
        return new Iterator<Integer>() {
            SingleNode node = head;
            
            @Override
            public boolean hasNext () {
                return node != null;
            }
            
            @Override
            public Integer next () {
                Integer v = node.value;
                node = node.next;
                return v;
            }
        };
    }
}
